import Koa, { Context, Next } from "koa";
import { koaSwagger } from "koa2-swagger-ui";
import Router from "@koa/router";
import yaml from "yaml";
import fs from "fs";
import path from "path";

export default (app: Koa) => {
  const yamlText = fs.readFileSync(
    path.join(process.cwd(), "./openapi.yaml"),
    "utf8"
  );

  const swaggerSpec = yaml.parse(yamlText);

  const r = new Router();
  r.prefix("/swagger");

  // swagger JSON 可以用于提取 TS
  r.get("/swagger.json", (ctx: Context, next: Next) => {
    ctx.body = swaggerSpec;
  });

  // 使用 swaggerSpec 生成 swagger 文档页面，并开放在指定路由。swagger访问前缀
  r.get(
    "/",
    koaSwagger({
      routePrefix: false, // 让 swagger 显示在 `/swagger` 而不是 `/swagger/`
      swaggerOptions: {
        spec: swaggerSpec,
        // 持久化存储 token 凭证
        persistAuthorization: true,
      },
    })
  );

  app.use(r.routes()).use(r.allowedMethods());
};
